package top.ewind.interceptor;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;

import io.moquette.spi.security.IAuthenticator;
import top.ewind.controller.common.RedisConstants;
/*import top.ewind.model.Device;
import top.ewind.model.DeviceProduct;*/
import top.ewind.util.SecurityUtil;

public class MsgAuthenticator implements IAuthenticator {
    public boolean checkValid(String clientId, String username, byte[] password){
    	String dpass = new String(password);
    	//管理员验证
    	//Client-ID：字符”admin/”+sys_admin.id
    	//Username：sys_admin.username
    	//Password：sys_admin.password
    	if(clientId.startsWith("admin/")){
    		Integer adminid = Db.queryInt("select id from sys_admin where username = ? and password =?",username,dpass);
    		return adminid!=null;
    	}
    	//用户认证
    	//Client-ID：字符”user/”+device_user.id
    	//Username：device_user.id
    	//Password：md5(user.userkey＋timestamp),timestamp 
    	if(clientId.startsWith("user/")){
    		String[] userid = clientId.split("/");
    		String[] parr = dpass.split(",");
    		if(userid[1]!=null&&parr.length==2){
    			Record devicebid = Db.findById("device_user",userid[1]);
    			if(devicebid!=null){
    				String md5key = SecurityUtil.md5(devicebid.getStr("userkey")+parr[1]);
    				return md5key.equals(parr[0]);
    			}
    		}
			return false;
    	}
    	//设备认证
    	//Client-ID：device.pid+”/”+device.id
    	//Username：device.id
    	//Password：md5(device_product.pmkey＋timestamp),timestamp 
    	else{
			Record device = Db.findById("device",username);
    		String[] parr = dpass.split(",");
    		if(device!=null&&parr.length==2){
    			Record deviceProduct = Db.findById("device_product",device.getStr("pid"));
    			if(deviceProduct!=null){
    				String md5key = SecurityUtil.md5(deviceProduct.getStr("pmkey")+parr[1]);
    				return md5key.equals(parr[0]);
    			}
    		}
			return false;
    	}
    }
}
